package com.frank.frankutils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import android.content.Context;
import android.util.Base64;

/**
 * 本地数据进行异或加密工具类
 * 
 * @author Frank
 * @version 1.0 Create by 2016.4.25
 */
public class LocalEncrpXORUtils {
	private final static String TAG = LocalEncrpXORUtils.class.getSimpleName();

	/**
	 * 异或加密和解密算法
	 * 
	 * @param is
	 * @param os
	 * @throws Exception
	 */
	public static void encodeAndDecode(InputStream is, OutputStream os)
			throws Exception {
		int bytes = -1;
		while ((bytes = is.read()) != -1) {
			bytes = bytes ^ 0xff;// 和0xff进行异或处理
			os.write(bytes);
		}
	}

	/**
	 * 加密
	 * 
	 * @param content
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static byte[] encodeContent(String content, Context context)
			throws Exception {
		InputStream is = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			is = new ByteArrayInputStream(content.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		try {
			encodeAndDecode(is, out);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}

	/**
	 * 解密
	 * 
	 * @param content
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static String decodeContent(byte[] buff) throws Exception {
		InputStream is = new ByteArrayInputStream(buff);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			encodeAndDecode(is, out);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new String(out.toByteArray(), "utf-8");
	}

	/**
	 * 加密或者解密
	 * 
	 * @param buff
	 * @return
	 * @throws Exception
	 */
	public static byte[] encodeAndDecodeContent(byte[] buff) throws Exception {
		InputStream is = new ByteArrayInputStream(buff);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			encodeAndDecode(is, out);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}
}
